﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    /// <summary>
    /// 串口帮助类
    /// </summary>
    public class ExSerialPort
    {
        SerialPort comDevice = new SerialPort();
        public event Action<string> DataReceived;

        public ExSerialPort(string portName)
        {
            comDevice.PortName = portName;
            comDevice.BaudRate = 9600;
            comDevice.Encoding = Encoding.Default;
            comDevice.Parity = Parity.None;
            comDevice.StopBits = StopBits.One;
            comDevice.DataBits = 8;

            comDevice.DataReceived += ComDevice_DataReceived;
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ComDevice_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] reDatas = new byte[comDevice.BytesToRead];
            comDevice.Read(reDatas, 0, reDatas.Length);//读取数据
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < reDatas.Length; i++)
            {
                sb.AppendFormat("{0:x2}" + " ", reDatas[i]);
            }

            DataReceived?.Invoke(sb.ToString().ToUpper());
        }

        /// <summary>
        /// 获取可用串口
        /// </summary>
        /// <returns></returns>
        public List<string> FindPorts()
        {
            string[] ports = SerialPort.GetPortNames();

            return new List<string>(ports);
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <returns></returns>
        public bool OpenSerialPort()
        {
            try
            {
                comDevice.Open();
                comDevice.DiscardInBuffer();
                comDevice.DiscardOutBuffer();

                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool CloseSerialPort()
        {
            try
            {
                comDevice.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
